<template>
  <NuxtLayout name="user" menuActive="2">
    <div class="box">
      <div class="box_title">更换手机号</div>
      <el-form :model="phoneForm" :rules="phoneFormRules" ref="phoneFormRef" label-width="120px">
        <el-form-item label="手机号">
          <el-input :value="userinfo.phoneNo" disabled style="width: 260px;" />
        </el-form-item>
        <el-form-item label="新号码" prop="newPhoneNo">
          <el-input v-model="phoneForm.newPhoneNo" maxlength="11" placeholder="请输入新号码" style="width: 260px;" />
        </el-form-item>
        <el-form-item label="验证码" prop="newPhoneCode">
          <el-input v-model="phoneForm.newPhoneCode" maxlength="6" placeholder="请输入验证码" style="width: 260px;">
            <template #append>
              <el-button :disabled="codeDisabled" @click="getCodeFn">{{ codeText }}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" :disabled="savePhoneDisabled" @click="savePhoneFn">保存手机号</el-button>
        </el-form-item>
      </el-form>
    </div>
  </NuxtLayout>
</template>

<script setup>
import { getPhoneCodeApi, updatePhoneNo } from '~/server/api'
// TDK
const prevHost = useRequestHeaders()["x-forwarded-proto"];
const host = useRequestHeaders()["host"];
const fullPath = useRoute()["fullPath"];
useSeoMeta({
  title: "技考邦_更换手机",
  keywords: "技考邦,更换手机",
  description: "技考邦，更换手机。",
  ogTitle: "技考邦_更换手机",
  ogDescription: "技考邦，更换手机。",
  ogType: "article",
  ogUrl: `${prevHost}://${host}${fullPath}`,
});
const userinfo = useRoute().meta.userinfo || {};
const phoneForm = reactive({
  newPhoneNo: '',
  newPhoneCode: ''
})
const savePhoneDisabled = ref(false)
const codeText = ref('获取验证码')
const codeDisabled = ref(false)
const codeTimer = ref(null)
const codeDownTime = ref(60)
const phoneFormRef = ref(null)
const phoneFormRules = {
  newPhoneNo: [
    { required: true, pattern: /^1[3456789]\d{9}$/, message: '请正确输入新的联系方式', trigger: 'blur' }
  ],
  newPhoneCode: [
    { required: true, len: 6, message: '验证码有误', trigger: 'blur' }
  ]
}
// 获取验证码
function getCodeFn(type) {
  if (!/^1[3456789]\d{9}$/.test(phoneForm.newPhoneNo) && !type) {
    ElMessage.warning('请输入新号码')
    return false
  }
  downTimeFn()
  useServerRequest(getPhoneCodeApi, {
    method: 'get',
    params: {
      phone: type === 'pwd' ? pwdForm.phoneNo : phoneForm.newPhoneNo
    }
  }).then(({ errno, errmsg }) => {
    if (errno === 0) {
      ElMessage.success('验证码发送成功，请注意查收')
      return false
    }
  })
}
// 倒计时
function downTimeFn() {
  codeDisabled.value = true;
  let t = localStorage.getItem('downTime') ? localStorage.getItem('downTime') : codeDownTime.value;
  codeText.value = `重新获取${t > 9 ? t : '0' + t}s`;
  codeTimer.value = setInterval(() => {
    t--;
    localStorage.setItem('downTime', t)
    codeText.value = `重新获取${t > 9 ? t : '0' + t}s`;
    if (t <= 0) {
      clearInterval(codeTimer.value)
      codeTimer.value = null;
      codeText.value = '获取验证码';
      codeDisabled.value = false;
      localStorage.removeItem('downTime')
    }
  }, 1000)
}
// 保存手机号
function savePhoneFn() {
  phoneFormRef.value.validate((vali) => {
    if (vali) {
      savePhoneDisabled.value = true;
      useServerRequest(updatePhoneNo, {
        method: 'post',
        body: JSON.stringify(phoneForm)
      }).then(({ errno, errmsg }) => {
        setTimeout(() => {
          savePhoneDisabled.value = false;
        }, 1500)
        if (errno === 0) {
          ElMessage.success('更改手机号成功')
          useRoute().meta.userinfo.phoneNo = phoneForm.newPhoneNo;
          phoneForm.newPhoneNo = '';
          phoneForm.newPhoneCode = '';
          return false
        }
      }).catch(err => {
        ElMessage.error(err)
        savePhoneDisabled.value = false;
      })
    } else {
      ElMessage.warning('请完善更换手机号表单')
      return false
    }
  })
}
// 挂载
onMounted(() => {
  if (localStorage.getItem('downTime')) {
    downTimeFn()
  }
})
</script>

<style lang="less" scoped>
.box {
  padding: 30px;

  &_title {
    font-size: 20px;
    color: #333333;
    margin-bottom: 30px;
  }
}
</style>